package com.example.treasure_back.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.treasure_back.mapper.UserClockMapper;
import com.example.treasure_back.model.UserClockModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserClockService {

    @Autowired
    private UserClockMapper userClockMapper;

    public Integer getTotalDaysByEmail(String email){
        UserClockModel userClockModel = userClockMapper.selectById(email);
        return userClockModel.getTotalDays();
    }

    public UserClockModel getUserClock(String email){
        UserClockModel userClockModel = userClockMapper.selectById(email);
        if (userClockModel != null){
            return userClockModel;
        }
        else{
            UserClockModel newUserClockModel = new UserClockModel();
            newUserClockModel.setEmail(email);
            newUserClockModel.setIsClock(0);
            newUserClockModel.setTotalDays(0);
            userClockMapper.insert(newUserClockModel);
            return newUserClockModel;
        }
    }

    public void updateDate(String email){
        UserClockModel userClockModel = userClockMapper.selectById(email);
        UpdateWrapper<UserClockModel> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("email",email);
        updateWrapper.set("is_clock",0);
        userClockMapper.update(userClockModel,updateWrapper);
    }

    public void changeClock(String email){
        UserClockModel userClockModel = userClockMapper.selectById(email);
        UpdateWrapper<UserClockModel> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("is_clock",1);
        updateWrapper.eq("email",email);
        updateWrapper.set("total_days",userClockModel.getTotalDays()+1);
        userClockMapper.update(userClockModel,updateWrapper);
    }
}
